<?php
/**
 * Validate log in.
 */

session_start();

require_once 'incs/database.php';
require_once 'config.php';

sleep(3);
if (!dataBase::connect(
        config::HOST,
        config::USERNAME,
        config::PASSWORD,
        config::NAME
    )) {
    $return['error'] = true;
    $return['msg'] = 'Failed to connect to database.';
}

$db = dataBase::getInstance();

while(true) {
    if (empty($_POST['email'])) {
        $return['error'] = true;
        $return['msg'] = 'You did not enter your email.';
        break;
    }

    if (empty($_POST['password'])) {
        $return['error'] = true;
        $return['msg'] = 'You did not enter your password.';
        break;
    }

    if (empty($_POST['tan'])) {
        $return['error'] = true;
        $return['msg'] = 'You did not enter your tan code.';
        break;
    }

    $sql = "SELECT `salt` "
    . "FROM `users` "
    . "WHERE `username` = '" . mysql_real_escape_string($_POST['email']) . "' "
    . "LIMIT 1";

    if (($rez = $db->query($sql)) === false) {
        $return['error'] = true;
        $return['msg'] = 'Failed to execute query.';
        break;
    }

    if (mysql_num_rows($rez) !== 1) {
        $return['error'] = true;
        $return['msg'] = 'Username with this e-mail does not exist.';
        break;
    }

    $salt = mysql_fetch_assoc($rez);

    $pass = md5($_POST['password']);
    $div = intval(32 / strlen($_POST['password']));
    $pass = md5(substr($pass, 0, $div)
    . $salt['salt']
    . substr($pass, $div));

    $sql = "SELECT `id` "
    . "FROM `users` "
    . "WHERE `username` = '" . mysql_real_escape_string($_POST['email']) . "' "
    . "AND `password` = '" . $pass . "'"
    . "LIMIT 1";

    if (($rez = $db->query($sql)) === false) {
        $return['error'] = true;
        $return['msg'] = 'Failed to execute query.';
        break;
    }

    if (mysql_num_rows($rez) !== 1) {
        $return['error'] = true;
        $return['msg'] = 'Your password is invalid.';
        break;
    }

    $id = mysql_fetch_assoc($rez);

    $sql = "SELECT * "
    . "FROM `tan_tables` "
    . "WHERE `row` = '" . $_SESSION['tan']['row'] . "'"
    . "AND `column` = '" . $_SESSION['tan']['column'] . "'"
    . "AND `value` = '" . md5($_POST['tan']) . "'"
    . "AND `user_id` = '" . $id['id'] . "'";

    break;
}

if (isset($return['error'])) {
    $row = rand(1, 6);
    $column = rand(1, 4);
    $_SESSION['tan'] = array(
        'row' => $row,
        'column' => $column
    );
    $return['tan'] = array(
        'row' => $row,
        'column' => $column
    );
}
else {
    $return['error'] = false;
    $return['msg'] = 'You are logged in.';
}

echo json_encode($return);
?>